import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { Form, Button, Row, Col } from 'antd';
import FormControls from '@/components/FormControls';

const getFormItemLabelCol = (item, max) => {
  let labelWidth = item.labelWidth || max.length * 16
  if (typeof labelWidth === 'number') {
    labelWidth += 'px'
  }
  return {
    style: {
      width: labelWidth
    }
  }
}

const collapseNum = 3; // 展开收起的数量

// 获取查询按钮占位
const getButtonsCol = (columns, isCollapse) => {
  const spans = columns
    .filter((item, index) => !isCollapse ? true : index + 1 <= collapseNum)
    .reduce((cur, next) => {
      const { itemSpan = 6 } = next
      return cur + itemSpan
    }, 0)
  const restCol = spans < 24 ? (24 - spans) : (24 - spans % 24)
  return restCol < 4 ? 4 : restCol
}

const TableForm = (props, ref) => {
  const { filterForm, searchConfig } = props;

  const maxLabel = filterForm.map(v => v.title).sort((a, b) => a?.length - b?.length)[filterForm.length - 1]

  const { defaultCollapsed = true } = searchConfig
  const [isCollapse, setIsCollapse] = useState(defaultCollapsed); //  默认 收起

  const [form] = Form.useForm();

  useImperativeHandle(ref, () => ({
    reset: () => {
      reset();
    },
  }));

  const submit = () => {
    const values = form.getFieldsValue();
    if (props.onSubmit) {
      props.onSubmit(values);
    }
  };

  const reset = () => {
    form.resetFields();
    if (props.onReset) {
      props.onReset();
    }
  };

  return (
    <div className='form-layout'>
      <Form
        form={form}
        onFinish={() => {
          submit();
        }}
      >
        <Row gutter={10} type="flex" align="middle">
          {filterForm.map(
            (item, index) =>
            { 
              const { formItemProps, onChange = () => {} } = item;
              return ((index + 1 > collapseNum && !isCollapse) || index + 1 <= collapseNum) && (
                <Col xxl={item.itemSpan || searchConfig.itemSpan || 6} xl={8} md={12} xs={24} key={item.dataIndex}>
                  <Form.Item
                    style={{ width: '100%' }}
                    label={formItemProps?.label || item.title}
                    labelCol={getFormItemLabelCol(item, maxLabel)}
                    initialValue={item.initialValue}
                    name={item.dataIndex}
                    {...formItemProps}
                  >
                    {FormControls.getControlComponent(item.valueType, { ...item })}
                  </Form.Item>
                </Col>
              )
            }
          )}
          {filterForm.length > 0 && (
            <Col xxl={getButtonsCol(filterForm, isCollapse)} xl={8} md={12} xs={24}>
              <div className='query-filter-actions'>
                <Button htmlType="submit" type="primary">
                  查询
                </Button>
                <Button
                  onClick={() => {
                    reset();
                  }}
                  style={{ marginLeft: 8 }}
                >
                  重置
                </Button>
                {filterForm.length > collapseNum && (
                  <div
                    className="collapse"
                    onClick={() => {
                      setIsCollapse((prvState) => !prvState);
                    }}
                  >
                    {isCollapse ? '展开' : '收起'}
                    <span className="table-form-action">
                      <svg
                        viewBox="64 64 896 896"
                        focusable="false"
                        data-icon="down"
                        width="1em"
                        height="1em"
                        fill="currentColor"
                        aria-hidden="true"
                      >
                        <path d="M884 256h-75c-5.1 0-9.9 2.5-12.9 6.6L512 654.2 227.9 262.6c-3-4.1-7.8-6.6-12.9-6.6h-75c-6.5 0-10.3 7.4-6.5 12.7l352.6 486.1c12.8 17.6 39 17.6 51.7 0l352.6-486.1c3.9-5.3.1-12.7-6.4-12.7z" />
                      </svg>
                    </span>
                  </div>
                )}
              </div>
            </Col>
          )}
        </Row>
      </Form>
    </div>
  );
};

export default forwardRef(TableForm);
